﻿﻿		$('#scheduleDateStart,#scheduleDateEnd').datetimepicker({
        viewType: "date",
        todayBtn: true
    });
		$('#searchForm').form().show();

		function showMore(target){
				var css = $(target).hasClass('glyphicon-option-horizontal') ? 'text-primary btn show glyphicon glyphicon-option-vertical' : 'text-primary btn show glyphicon glyphicon-option-horizontal';
				$(target).attr('class',css).prev('.drop_list').toggle("fast");
		};
		var getStateCount = function selectStateCount(dmTaskId){
			 
			 queryParam = {dmTaskId:dmTaskId}; 
     	 $.ajax({
	       	url: webRoot+'taskgenerator/dmtaskstage/selectStateCount.do',
					data: queryParam, 
					async : true,
		      type : 'POST',
		      }).done(function(serverData, textStatus, jqXHR) {
		         var data = eval("(" + jqXHR.responseText + ")");
		         //$('#dialog-grid-count').grid("reloadData",data);
		   			 document.getElementById("labnos0").innerHTML= "("+data[0]+")";  
		   			 document.getElementById("labnos1").innerHTML= "("+data[1]+")"; 
		   			 document.getElementById("labnos2").innerHTML= "("+data[2]+")"; 
		   			 document.getElementById("labnos3").innerHTML= "("+data[3]+")"; 
		   			 document.getElementById("labnos4").innerHTML= "("+data[4]+")";       
		         return false;
		     })
		     .fail(function() {
		         fish.toast('error','网络连接失败');
		     }).always(function() {
		     	$.unblockUI();
		     });
	     return false;
		}	
		function refreshGrid(dmTaskId,state,obj) {
		    var newData = getDisDialogData(dmTaskId,state);
		    var count = getStateCount(dmTaskId); 
		    $.blockUI({message : "数据载入中,请稍候..."});
		    $('.ui-dialog .panel-body .custom_a_btn').removeClass('active');
		    $(obj).addClass('active');
		    $('#dialog-grid').grid("reloadData",newData); //重新加载数据
		    console.log(count)
		    

		    //$('#dialog-grid-count').grid("reloadData",count); //重新加载数据
		};
		// 请求服务器获取数据的方法
		var getDisDialogData = function(dmTaskId, state) { // 请求服务器获取数据的方法
		    queryParam = {dmTaskId:dmTaskId,state:state};
	        $.ajax({
	           url: webRoot+'taskgenerator/dmtaskstage/selectListInfo.do',
	           async : true,
	           type : 'POST',
	           data :queryParam
	        }).done(function(serverData, textStatus, jqXHR) {
	           var data = eval("(" + jqXHR.responseText + ")");
	           $('#dialog-grid').grid("reloadData",data); 
	           return false;
	       })
	       .fail(function() {
	           fish.toast('error','网络连接失败');
	       }).always(function() {
	       	$.unblockUI();
	       });
	       return false;
	   };
	   var getMyData3 = function(dmInfoId,state)  {// 请求服务器获取数据的方法
		    queryParam = {dmInfoId:dmInfoId,state:state};
	        $.ajax({
	           url: webRoot+'taskgenerator/dmtaskstage/qryLeftErrorInfo.do',
	           async : true,
	           type : 'POST',
	           data :queryParam
	        }).done(function(serverData, textStatus, jqXHR) {
	           var data = eval("(" + jqXHR.responseText + ")");
	           $('#dialog-info-grid1').grid("reloadData",data); 
	           return false;
	       })
	       .fail(function() {
	           fish.toast('error','网络连接失败');
	       }).always(function() {
	       	$.unblockUI();
	       });
	       return false;
	   };
	   var getMyData4 = function(dmInfoId,state) { // 请求服务器获取数据的方法
		    queryParam = {dmInfoId:dmInfoId,state:state};
	        $.ajax({
	           url: webRoot+'taskgenerator/dmtaskstage/qryRightErrorInfo.do',
	           async : true,
	           type : 'POST',
	           data :queryParam
	        }).done(function(serverData, textStatus, jqXHR) {
	           var data = eval("(" + jqXHR.responseText + ")");
	           $('#dialog-info-grid2').grid("reloadData",data); 
	           return false;
	       })
	       .fail(function() {
	           fish.toast('error','网络连接失败');
	       }).always(function() {
	       	$.unblockUI();
	       });
	       $.blockUI({message : "数据载入中,请稍候..."});
	       return false;
	   };
		function showDialog(n,d,e,obj){
			var dmTaskId = rowData[d].dmTaskId;
			var operType = rowData[d].operType;
			var state;
			
			if(n==0){
				state=null
			}else if(n==1){
				state='00A'
			}else if(n==2){
				state='00R'
			}else if(n==3){
				state='00T'
			}else if(n==4){
				state='00F'
			}
			var $dialog;
			var tpl = '<div class="ui-dialog panel panel-default"><div class="modal-header">【'+rowData[d].planName+'> '+rowData[d].taskName+'> 执行明细】</div>';
				tpl += '<span class="close text-muted glyphicon glyphicon-remove"></span>';
				tpl += '<div id="dialog-grid-count" class="panel-body">';
				tpl += '<a class="custom_a_btn a_primary'+(n==0 ? ' active':'')+'" href="javascript:void(0);" onclick="refreshGrid('+dmTaskId+',null,this)">全部<span id="labnos0">('+rowData[d].goingDetail[0]+')</span></a>';
				tpl += '<a class="custom_a_btn a_sucess'+(n==1 ? ' active':'')+'" href="javascript:void(0);" onclick="refreshGrid('+dmTaskId+',\'00A\',this)">执行完成<span id="labnos1">('+rowData[d].goingDetail[1]+')</span></a>';
				tpl += '<a class="custom_a_btn a_warning'+(n==2 ? ' active':'')+'" href="javascript:void(0);" onclick="refreshGrid('+dmTaskId+',\'00R\',this)">执行中<span id="labnos2">('+rowData[d].goingDetail[2]+')</span></a>';
				tpl += '<a class="custom_a_btn a_hold'+(n==3 ? ' active':'')+'" href="javascript:void(0)" onclick="refreshGrid('+dmTaskId+',\'00T\',this)">待执行<span id="labnos3">('+rowData[d].goingDetail[3]+')</span></a>';
				tpl += '<a class="custom_a_btn a_danger'+(n==4 ? ' active':'')+'" href="javascript:void(0);" onclick="refreshGrid('+dmTaskId+',\'00F\',this)">执行失败<span id="labnos4">('+rowData[d].goingDetail[4]+')</span></a>';
				tpl += '<div id="dialog-grid" class="custom2-ui-jqgrid"></div>';
				tpl += '</div>';
				tpl += '</div>';
			$dialog = $(tpl).appendTo('body');
			var $close = $dialog.find('.close');
			var $grid = $dialog.find('#dialog-grid');
			$grid.grid(setDialogOpt(dmTaskId,operType,state));
			$dialog.dialog({
				canClose:false,
				show:true,
				width:900,
				resizable:true,
				hide:true,
				modal: true
			});
			$close.click(function(){				
				$dialog.dialog('close').remove();
				page = $("#monitor_jqGrid").jqGrid("getGridParam","page");
			  getPerData2(page);
			});
			
		};
			
				//备份或者清理数据的问题列表
			function testbackcellval(cellval, opts, rwdat, _act){
				var tpl = '';
				if(rwdat.dataType==2){
					if(rwdat.stage==1&&rwdat.checkupCount>rwdat.backupCount&&(rwdat.state=='00A'||rwdat.state=='00F')){
						tpl = cellval+'&nbsp;<a href="javascript:void(0)" onclick="errorInfoFile(\'备份\','+rwdat.dmInfoId+',\'00F\')" class="text-danger glyphicon glyphicon-info-sign"></a>';
					}else{
						tpl = cellval;
					}
				}else{
					if(rwdat.stage==1&&rwdat.checkupCount>rwdat.backupCount&&(rwdat.state=='00A'||rwdat.state=='00F')){
						tpl = cellval+'&nbsp;<a href="javascript:void(0)" onclick="errorInfo(\'备份\','+rwdat.dmInfoId+',\'0BF\')" class="text-danger glyphicon glyphicon-info-sign"></a>';
					}else{
						tpl = cellval;
					}
				}
				
				return tpl;
			}
			function testcleancellval(cellval, opts, rwdat, _act){
				var tpl = '';
				if(rwdat.dataType==2){
					if(rwdat.stage==2&&rwdat.cleanupCount<rwdat.backupCount&&(rwdat.state=='00A'||rwdat.state=='00F')){
						tpl = cellval+'&nbsp;<a href="javascript:void(0)" onclick="errorInfoFile(\'清理\','+rwdat.dmInfoId+',\'00F\')" class="text-danger glyphicon glyphicon-info-sign"></a>';
		
					}else{
						tpl = cellval;
						}
				}else{
					if(rwdat.stage==2&&rwdat.cleanupCount<rwdat.backupCount&&(rwdat.state=='00A'||rwdat.state=='00F')){
						tpl = cellval+'&nbsp;<a href="javascript:void(0)" onclick="errorInfo(\'清理\','+rwdat.dmInfoId+',\'0CF\')" class="text-danger glyphicon glyphicon-info-sign"></a>';
		
					}else{
						tpl = cellval;
						}
				}
				
				return tpl;
				}
				
			function setDialogOpt(dmTaskId,operType,state){
				var dialog_opt = {
				datatype: "json",
				colModel:[
					{name:'checkObjName',label:'处理数据',width:175,sortable:false},
					{name:'stage',label:'环节',width:80,sortable:false,align:'center',formatter:function(cellval){return cellval==0 ? '体检' : (cellval==1 ?'备份':(cellval==2 ? '清理' : '-'))}},
					{name:'state',label:'当前状态',width:120,sortable:false,align:'center',formatter:function(cellval, opts, rwdat, _act){ return zhuangtaiFormatter(operType,cellval, opts, rwdat, _act);}},
					{name:'checkupCount',label:'体检',width:80,sortable:false,title:false,align:'center',formatter:function(cellval){ return cellval}},		
					{name:'backupCount',label:'备份',width:80,sortable:false,align:'center',formatter:function(cellval, opts, rwdat, _act){ return testbackcellval(cellval, opts, rwdat, _act);}},
					{name:'cleanupCount',label:'清理',width:80,sortable:false,align:'center',formatter:function(cellval, opts, rwdat, _act){ return testcleancellval(cellval, opts, rwdat, _act);}},
					{name:'taskStartTime',label:'开始时间',width:140,sortable:false,align:'center',classes:'text-muted'},
					{name:'taskEndTime',label:'预计完成时间',width:140,sortable:false,align:'center',classes:'text-muted'}//,formatter:'actions',formatoptions:{delbutton: true,}
				],
//		  viewrecords: false,//是否显示记录描述
				height:340,
				autowidth:true,
				//width:100%,
				autoResizable:true,
				scrollOffset:0,
				server: true,
			  jsonReader : {
		            root: "resultList",// json中代表实际模型数据的入口  
		            repeatitems: false,// 如果设为false，则jqGrid在解析json时，会根据name来搜索对应的 数据元素（即可以json中元素可以不按顺序）；而所使用的name是来自于colModel中的name设定。
		            cell: "cell",
		            id: "dmInfoId"
		        },
			  pageData: getDisDialogData(dmTaskId,state) ,//同步场景直接用getPerData,通过 jQuery("#jqGrid01").jqGrid("reloadData",getPerData(1));加载数据;异步场景用getPerData2
				forceFit:true,  //当为ture时,调整列宽度不会改变表格的宽度
				gridview : false
			};
			return dialog_opt;
		}
		function setMydata3Opt(dmInfoId,state){
			var mydata3_opt = {
				data:getMyData3(dmInfoId,state),
				colModel:[
					{name:'dmObjectName',label:'数据名称',width:95,sortable:false},
					{name:'errorDesc',label:'错误类型',width:195,sortable:false,align:'center'},
					{name:'count',label:'错误数',width:50,sortable:false,align:'center'}
				],
				height:380,
				//width:100%,
				autowidth:true,
				scrollOffset:0,
				server: true
			};
			 $.blockUI({message : "数据载入中,请稍候..."});
			return mydata3_opt;
		}
		function setMydata4Opt(dmInfoId,state){
			var mydata4_opt = {
			data:getMyData4(dmInfoId,state),
			colModel:[
				{name:'state',label:'环节',width:40,sortable:false,formatter:function(cellval){return cellval=='0BF' ? '备份' : (cellval=='0CF' ?'清理': '-')}},
				{name:'dmObjectName',label:'数据名称',width:80,sortable:false,align:'center'},
				{name:'dmObjectKeyName',label:'关键字段',width:80,sortable:false,align:'center'},
				{name:'dmObjectKeyValue',label:'关键字段值',width:80,sortable:false,title:false,align:'center'},
				{name:'errorDesc',label:'错误描述',width:265,sortable:false,align:'center'}			
			],
			height:380,
			autowidth:true,
		//width:100%,
			autoResizable:true,
			scrollOffset:0,
			server: true
			};
			$.blockUI({message : "数据载入中,请稍候..."});
			return mydata4_opt;	
		}
			
		function errorInfo(txt,dmInfoId,state){
			var $dialog;
			var tpl = '<div class="ui-dialog panel panel-default"><h4 class="modal-header text-danger">【 '+txt+' 】环节错误明细</h4>';
				tpl += '<span class="close text-muted glyphicon glyphicon-remove"></span>';
				tpl += '<div class="col-sm-5 row"><div id="dialog-info-grid1" class="custom2-ui-jqgrid"></div></div>';
				tpl += '<div class="col-sm-7 row"><div id="dialog-info-grid2" class="custom2-ui-jqgrid"></div></div>';
				tpl += '</div>';
				tpl += '</div>';
				$dialog = $(tpl).appendTo('body');
			var $close = $dialog.find('.close');
			var $grid1 = $dialog.find('#dialog-info-grid1');
			var $grid2 = $dialog.find('#dialog-info-grid2');
			$grid1.grid(setMydata3Opt(dmInfoId,state));
			$grid2.grid(setMydata4Opt(dmInfoId,state));

			$dialog.dialog({
				canClose:false,
				show:true,
				resizable:true,
				width:900,
				hide:true,
				modal: true
			});

			$close.click(function(){
				$dialog.dialog('close').remove();
			});
		};

		function errorInfoFile(txt,dmInfoId,state){
			var $dialog;
			var tpl = '<div class="ui-dialog panel panel-default"><h4 class="modal-header text-danger">【 '+txt+' 】环节错误明细</h4>';
				tpl += '<span class="close text-muted glyphicon glyphicon-remove"></span>';
				tpl += '<div class="col-sm-5 row"><div id="dialog-info-grid1" class="custom2-ui-jqgrid"></div></div>';
				tpl += '<div class="col-sm-7 row"><div id="dialog-info-grid2" class="custom2-ui-jqgrid"></div></div>';
				tpl += '</div>';
				tpl += '</div>';
				$dialog = $(tpl).appendTo('body');
			var $close = $dialog.find('.close');
			var $grid1 = $dialog.find('#dialog-info-grid1');
			var $grid2 = $dialog.find('#dialog-info-grid2');
			$grid1.grid(setMydata3OptFile(dmInfoId,state));
			$grid2.grid(setMydata4OptFile(dmInfoId,state));

			$dialog.dialog({
				canClose:false,
				show:true,
				resizable:true,
				width:900,
				hide:true,
				modal: true
			});

			$close.click(function(){
				$dialog.dialog('close').remove();
			});
		};
		function setMydata3OptFile(dmInfoId,state){
			var mydata3_opt = {
				data:getMyData3File(dmInfoId,state),
				colModel:[
					{name:'shell_script',label:'SHELL执行命令',width:95,sortable:false},
					{name:'errorDesc',label:'错误类型',width:195,sortable:false,align:'center'},
					{name:'count',label:'错误数',width:50,sortable:false,align:'center'}
				],
				height:380,
				//width:100%,
				autowidth:true,
				scrollOffset:0,
				server: true
			};
			 $.blockUI({message : "数据载入中,请稍候..."});
			return mydata3_opt;
		}
		function setMydata4OptFile(dmInfoId,state){
			var mydata4_opt = {
			data:getMyData4File(dmInfoId,state),
			colModel:[
				{name:'state',label:'环节',width:40,sortable:false,formatter:function(cellval){return cellval=='0BF' ? '备份' : (cellval=='0CF' ?'清理': '-')}},
				{name:'shellScript',label:'SHELL执行命令',width:200,sortable:false,align:'center'},
				/*{name:'dmObjectKeyName',label:'关键字段',width:80,sortable:false,align:'center'},
				{name:'dmObjectKeyValue',label:'关键字段值',width:80,sortable:false,title:false,align:'center'},
*/				{name:'errorDesc',label:'错误描述',width:150,sortable:false,align:'center'}			
			],
			height:380,
			autowidth:true,
		//width:100%,
			autoResizable:true,
			scrollOffset:0,
			server: true
			};
			$.blockUI({message : "数据载入中,请稍候..."});
			return mydata4_opt;	
		}
		var getMyData3File = function(dmInfoId,state)  {// 请求服务器获取数据的方法
		    queryParam = {dmInfoId:dmInfoId,state:state};
	        $.ajax({
	           url: webRoot+'taskgenerator/dmtaskstage/qryLeftErrorInfoFile.do',
	           async : true,
	           type : 'POST',
	           data :queryParam
	        }).done(function(serverData, textStatus, jqXHR) {
	           var data = eval("(" + jqXHR.responseText + ")");
	           $('#dialog-info-grid1').grid("reloadData",data); 
	           return false;
	       })
	       .fail(function() {
	           fish.toast('error','网络连接失败');
	       }).always(function() {
	       	$.unblockUI();
	       });
	       return false;
	    };
	    var getMyData4File = function(dmInfoId,state) { // 请求服务器获取数据的方法
		    queryParam = {dmInfoId:dmInfoId,state:state};
	        $.ajax({
	           url: webRoot+'taskgenerator/dmtaskstage/qryRightErrorInfoFile.do',
	           async : true,
	           type : 'POST',
	           data :queryParam
	        }).done(function(serverData, textStatus, jqXHR) {
	           var data = eval("(" + jqXHR.responseText + ")");
	           $('#dialog-info-grid2').grid("reloadData",data); 
	           return false;
	       })
	       .fail(function() {
	           fish.toast('error','网络连接失败');
	       }).always(function() {
	       	$.unblockUI();
	       });
	       $.blockUI({message : "数据载入中,请稍候..."});
	       return false;
	    };
		function toPercent(data){
		    var strData = parseFloat(data)*100;
		    var ret = strData.toFixed(2).toString()+"%";
		    return ret;
		}
		function zhuangtaiFormatter(operType,cellval, opts, rwdat, _act){
			var w ;
			var tpl;				
			if(cellval=='00R'){
				if(rwdat.stage==0){
						if(rwdat.totalRecordCount==0||rwdat.totalRecordCount==null){
								w=Math.round(0);
							}else{
								w=Math.round((rwdat.checkupCount/rwdat.totalRecordCount)*100);
								}		
						
						tpl ='<div class="text-a_progress">执行中<span class="text-muted">('+toPercent(rwdat.checkupCount/rwdat.totalRecordCount)+')</span></div>';
				}else if(rwdat.stage==1){
						if(rwdat.checkupCount==0||rwdat.checkupCount==null){
									w=Math.round(0);
							}else{
									w=Math.round((rwdat.backupCount/rwdat.checkupCount)*100);
								}		
						tpl ='<div class="text-a_progress">执行中<span class="text-muted">('+toPercent(rwdat.backupCount/rwdat.checkupCount)+')</span></div>';
				}else{
					if(operType==1){
						if(rwdat.checkupCount==0||rwdat.checkupCount==null){
									w=Math.round(0);
							}else{
								w=Math.round((rwdat.cleanupCount/rwdat.checkupCount)*100);
								}					
							tpl ='<div class="text-a_progress">执行中<span class="text-muted">('+toPercent(rwdat.cleanupCount/rwdat.checkupCount)+')</span></div>';
						}else{
							if(rwdat.backupCount==0||rwdat.backupCount==null){
									w=Math.round(0);
							}else{
							  	w=Math.round((rwdat.cleanupCount/rwdat.backupCount)*100);
								}
								
							tpl ='<div class="text-a_progress">执行中<span class="text-muted">('+toPercent(rwdat.cleanupCount/rwdat.backupCount)+')</span></div>';
						}
				}
				tpl += '<div class="a_progress"><div class="progress-bar" style="width:'+w+'%"></div></div>';
			}else if(cellval=='00T'){
			  tpl ='<div class="text-a_hold">待执行<span class="text-muted"></span></div>';
			}else if(cellval=='00A'){
				 tpl ='<div class="text-a_sucess">已完成<span class="text-muted">(100%)</span></div>';
			}else if(cellval=='00F'){
				 tpl ='<div class="text-a_danger">失败<span class="text-muted"></span></div>';
			}else if(cellval=='00X'){
				 tpl ='<div class="text-a_danger">取消<span class="text-muted"></span></div>';
			}else if(cellval=='00S'){
				 tpl ='<div class="text-a_sucess">数据恢复完成<span class="text-muted">(100%)</span></div>';
			}else if(cellval=='0SF'){
				 tpl ='<div class="text-a_danger">数据恢复失败<span class="text-muted"></span></div>';
			}else if(cellval=='0DS'){
				 tpl ='<div class="text-a_danger">数据恢复中<span class="text-muted"></span></div>';
			}
		
		
			return tpl;
		};

		function planGoingFormatter(cellval, opts, rwdat, _act){
			var tpl='';
			var taskCheck=rwdat.taskCheck;
			var resu='';
			if(taskCheck==1){
				resu='(审核拒绝)';					
			}else if(taskCheck==2){
				resu='(待审核)';
				if(rwdat.goingDetail[1] > 0 && rwdat.goingDetail[2] == 0){ //modified by lwb 去掉 2015/12/30 [790052]【数据管理大师】一期版本优化项--跟踪单（系统监控）
					resu='(待审核)';
					}else{
						resu='';
						}
			}else{
				resu='';	
			}
				if(rwdat.taskState=='00R'){ //执行中
			var w = Math.round((rwdat.goingDetail[1]/rwdat.goingDetail[0])*100);
			  tpl ='<div class="text-a_sucess">执行中<span class="text-muted">('+rwdat.goingDetail[1]+'/'+rwdat.goingDetail[0]+')</span></div>';
				tpl += '<div class="a_progress"><div class="progress-bar" style="width:'+w+'%"></div></div>';
			}else if(rwdat.taskState=='00T'){ //待执行
				tpl ='<div class="text-a_hold">待执行'+resu+'</div>';
				}else if(rwdat.taskState=='00A'){ //已完成
				tpl ='<div class="text-a_sucess">已完成'+resu+'</div>';
				}else if(rwdat.taskState=='00C'){ //已取消
				tpl ='<div class="text-a_danger">取消</div>';
				}else if(rwdat.taskState=='00F'){ //失败
				tpl ='<div class="text-a_danger">失败</div>';
				}else if(rwdat.taskState=='00P'){ //立即暂停
				tpl ='<div class="text-a_hold">立即暂停</div>';
				}else if(rwdat.taskState=='01P'){ //延时暂停
				tpl ='<div class="text-a_hold">延时暂停</div>';
				}else if(rwdat.taskState=='02P'){ //系统暂停
				tpl ='<div class="text-a_hold">系统暂停</div>';
				}else if(rwdat.taskState=='0DC'){ //系统暂停
				tpl ='<div class="text-a_hold">取消中</div>';
				}else if(rwdat.taskState=='0DP'){ //系统暂停
				tpl ='<div class="text-a_hold">暂停中</div>';
				}else if(rwdat.taskState=='0DS'){ //系统暂停
				tpl ='<div class="text-a_hold">数据恢复中</div>';
				}else if(rwdat.taskState=='00S'){ //系统暂停
				tpl ='<div class="text-a_sucess">数据恢复完成'+resu+'</div>';
				}else if(rwdat.taskState=='0SF'){ //系统暂停
				tpl ='<div class="text-a_danger">数据恢复失败</div>';
				}
			return tpl;
		};
			rowData=[];
			function goingDetailFormatter(cellval, opts, rwdat, _act){
			// 0:全部 1:执行完成 2:执行中 3:待执行 4:执行失败
			rowData[rwdat.dmTaskId] = rwdat;
			rowData[rwdat.operType] = rwdat;
			//onclick="aaaaa('+rwdat.dmTaskId+')"
			var tpl = '<a class="custom_a_btn a_primary" href="javascript:void(0);showDialog(0,'+rwdat.dmTaskId+','+rwdat.operType+',this)">全部<span>('+cellval[0]+')</span></a>'; 
				tpl += '<a class="custom_a_btn a_sucess" href="javascript:void(0);showDialog(1,'+rwdat.dmTaskId+','+rwdat.operType+',this)">执行完成<span>('+cellval[1]+')</span></a>';
				tpl += '<a class="custom_a_btn a_warning" href="javascript:void(0);showDialog(2,'+rwdat.dmTaskId+','+rwdat.operType+',this)">执行中<span>('+cellval[2]+')</span></a>'; 
				tpl += '<a class="custom_a_btn a_hold" href="javascript:void(0);showDialog(3,'+rwdat.dmTaskId+','+rwdat.operType+',this)">待执行<span>('+cellval[3]+')</span></a>'; 
				tpl += '<a class="custom_a_btn a_danger" href="javascript:void(0);showDialog(4,'+rwdat.dmTaskId+','+rwdat.operType+',this)">执行失败<span>('+cellval[4]+')</span></a>'; 
			
			return tpl;
		};
		function monitorDetailFormatter(cellval, opts, rwdat, _act){
				var tpl = '';
				if(cellval!=null){
//					for(var i=0; i < (cellval.length > 3 ? 3 : cellval.length); i++){
//						tpl += '<h5>'+cellval[i]+'</h5>';
//					}
					if(cellval.length > 3){
						for(var i=0; i < 3; i++){
  					tpl += '<h5>'+cellval[i]+'</h5>';
					}
						tpl += '<div class="drop_list" style="display:none">';
						for(var i=3; i < cellval.length; i++){
							tpl += '<h5>'+cellval[i]+'</h5>';
						}
						tpl += '</div>'	;
						tpl += '<span title="点击显示更多..." class="text-primary btn show glyphicon glyphicon-option-horizontal" onclick="showMore(this)" style="margin-top:-5px"></span>';

					}else{
						for(var i=0; i < cellval.length; i++){
						tpl += '<h5>'+cellval[i]+'</h5>';
						}
					}
									
				}
				return tpl;
		};
		
		
		//查询表单
		$('#searchForm').form().show();
		// 请求服务器获取数据的方法
		var getPerData = function(page, rowNum, sortname, sortorder) { // 请求服务器获取数据的方法
		   	$("#monitor_jqGrid").jqGrid("getGridParam","rowNum");
		   	$("#monitor_jqGrid").jqGrid("setGridParam",{page:page});
		   	rowNum = rowNum || $("#monitor_jqGrid").jqGrid("getGridParam","rowNum");
	        page = $("#monitor_jqGrid").jqGrid("getGridParam","page");
	        start = (page-1)*rowNum;
	        start = start<0?0:start;
	       
	        var queryParam = {};
	        //queryParam =  $('#searchForm').form('value');//序列化表格内容为字符串
	        
	        queryParam.nodeId = $('input[name="nodeId"]').attr("vId");
	        queryParam.state = $('#state').val();
	        queryParam.stage = $('#stage').val();
	        queryParam.planName = $('#planName').val();
	        queryParam.scheduleDateStart = $("#scheduleDateStart").datetimepicker("value");
	        queryParam.scheduleDateEnd = $("#scheduleDateEnd").datetimepicker("value");
	        fish.extend(queryParam,{page: JSON.stringify($("#monitor_jqGrid").jqGrid("getGridParam","page")),
	               limit : rowNum,
	               start : start});
	        $.ajax({
	           url: webRoot+'taskgenerator/dmtaskstage/queryListByPage.do',
	           async : true,
	           type : 'POST',
	           data :queryParam
	        }).done(function(serverData, textStatus, jqXHR) {
	           var data = eval("(" + jqXHR.responseText + ")");
	           jQuery("#monitor_jqGrid").jqGrid("reloadData",data);
	           return false;	           
	       })
	       .fail(function() {
	           fish.toast('error','网络连接失败');
	       }).always(function() {
	       	$.unblockUI();
	       });
	        pauseTask();	       
	       return false;
	   };
	   //默认加载
	   var getPerData2 = function(page, sortname, sortorder) {
		    _.delay(function(){
		        var result = getPerData(page, sortname, sortorder);
		        jQuery("#monitor_jqGrid").jqGrid("reloadData",result);
		    }, 100);
		     $.blockUI({message : "数据载入中,请稍候..."});
		    return false;
		};

		function pauseTask(){
			queryParam = {};
		  queryParam.nodeId = $('input[name="nodeId"]').attr("vId");
      queryParam.state = $('#state').val();
      queryParam.stage = $('#stage').val();
      queryParam.planName = $('#planName').val();
      queryParam.scheduleDateStart = $("#scheduleDateStart").datetimepicker("value");
      queryParam.scheduleDateEnd = $("#scheduleDateEnd").datetimepicker("value");
	    //queryParam =  $('#searchForm').form('value');//序列化表格内容为字符串
			$.ajax({
				url: webRoot+'taskgenerator/dmtaskstage/queryListCount.do',
				data: queryParam, 
				async : true,
	      type : 'POST',
				success : function(result){ 
					$("#pauseTask").text(result[4]); 
					$("#runningTask").text(result[0]); 
					$("#doneTask").text(result[2]); 
					$("#failureTask").text(result[3]); 
					$("#todoTask").text(result[1]); 
				} 
			}); 
		}	
		$(document).ready(function() {
			$('#scheduleDateStart').datetimepicker();
			$('#scheduleDateEnd').datetimepicker();
			$('#resetBtn').click(function() {
				$('input[name="nodeId"]').attr("vId","");	
			});
			$('input[name="stage"]').combobox({
				placeholder : "全部",
				dataTextField : "name",
				dataValueField : "value",
				value : "",
				dataSource : [{
							name : "全部",
							value : ""
						}, {
							name : "体检",
							value : "0"
						}, {
							name : "备份",
							value : "1"
						}, {
							name : "清理",
							value : "2"
						}]
			});
			$('input[name="state"]').combobox({
				placeholder : "全部",
				dataTextField : "name",
				dataValueField : "value",
				value : "",
				dataSource : [{
					name : "全部",
					value : ""
				}, {
					name : "待执行",
					value : "00T"
				}, {
					name : "执行中",
					value : "00R"
				}, {
					name : "暂停",
					value : "00P"
				}, {
					name : "取消",
					value : "00C"
				}, {
					name : "失败",
					value : "00F"
				}, {
					name : "已完成",
					value : "00A"
				}]
			});
			$('#nodeId').next(".input-group-addon").click(function() {
				$("#nodeId").val("");
				$('input[name="nodeId"]').attr("vId","");
			});
			
			// 所属系统，下拉树
	var nodeId_setting = {
		async: {
			enable: true,
			contentType: "application/json",
			url: webRoot + 'common/sysModule/queryAllForTree.do',
//			url: 'nodes.jsp',
			type: 'post'
		},
		view: {
			dblClickExpand:false,
			selectedMulti: false //如果为true,按住ctrl可以多选，false为单选 
			
		},
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "pId",
				rootPId: 0,
				iconSkin:"icon01"
			}
		},
		callback: {
			onClick: nodeIdonClick
		}
	};
	var nodeIdTree = $.fn.zTree.init($("#nodeId_tree"), nodeId_setting);
	var nodeIdTreeObj = $.fn.zTree.getZTreeObj("nodeId_tree");
	function nodeIdonClick(){
		nodes = nodeIdTree.getSelectedNodes();
		var nodeIdInput = $('input[name="nodeId"]');
		// 设置控件的其他属性：vId，为真正的value
		nodeIdInput.attr("vId",nodes[0].id).val(nodes[0].name);
		hideNodeIdTree();
	};
	$('input[name="nodeId"]').click(function(){
		var inputObj = $('input[name="nodeId"]');
		var	inputObjOffSet = $('input[name="nodeId"]').offset();
			$("#nodeId_commbox_tree").css({left:inputObjOffSet.left + "px", top:inputObjOffSet.top + inputObj.outerHeight() + "px",width:inputObj.outerWidth() + "px",'z-index':9999}).slideDown("fast");
			$("body").bind("mousedown", onBodyDownNode);
	});
	function onBodyDownNode(event) {
		if (!(event.target.name == "nodeId" || event.target.id == "nodeId_commbox_tree" || $(event.target).parents("#nodeId_commbox_tree").length>0)) {
			hideNodeIdTree();
		}
	};
		function hideNodeIdTree(){
			$("#nodeId_commbox_tree").fadeOut("fast");
			$("body").unbind("mousedown", onBodyDownNode);
		};  

	//首页跳转到监控页面，设置默认状态
	if(""!=state){
		$('input[name="state"]').combobox('value',state);//下拉框操作类型赋值
	}
	if(""!=stage){
		$('input[name="stage"]').combobox('value',stage);//下拉框操作类型赋值
	}
	if(time!=0&&"null"!=time){
		var myDate=new Date();
		if(time==-1){
			myDate.setYear(2000);
			myDate.setMonth(00);
			myDate.setDate(01);
		}else{
			myDate.setMonth(myDate.getMonth()-time);
		}
		$("#scheduleDateStart").datetimepicker("value",myDate);
	}
		//查询按钮
    $('#searchBtn').click(function(e) {
        var result = getPerData(1);
          $.blockUI({message : "数据载入中,请稍候..."});
    });
    
   var ck = $('#refresh').find('input[type="checkbox"]');

   if( ck.prop('checked')){
   		timeoutId = setInterval(refreshT,10*60*1000);
   	}
    $('#refresh').click(function(){
				ck.prop('checked') ? ck.prop('checked',false) : ck.prop('checked',true);
			if(ck.prop('checked')){	
					timeoutId = setInterval(refreshT,$("input[id=timeRef]").val()*60*1000);	
			}else{
				clearInterval(timeoutId);
				}
		});

		function refreshT(){
			 var result = getPerData(1);
			 
	  	 jQuery("#monitor_jqGrid").jqGrid("reloadData",result);
		}
			var monitoring_opt = {
					datatype: "json",
					colModel:[
						{name:'planName',label:'计划名称',width:'15%',sortable:false,formatter:function(cellval, opts, rwdat, _act){ 
							if(rwdat.effDate>rwdat.sysDate){
								return '<label class="checkbox-inline"><input type="checkbox" labelId='+rwdat.dmPlanId+'><div class="text-a_hold">(未生效)'+cellval+'</div></label>';
							}else if(rwdat.expDate<rwdat.sysDate){
								return '<label class="checkbox-inline"><input type="checkbox" labelId='+rwdat.dmPlanId+'><div class="text-a_danger">(失效)'+cellval+'</div></label>';
							}else{
								return '<label class="checkbox-inline"><input type="checkbox" labelId='+rwdat.dmPlanId+'>'+cellval+'</label>';
							}					
						}},
						{name:'sysDate',label:'系统日期',width:'12%',sortable:false,align:'center',hidden:true},
						{name:'effDate',label:'生效日期',width:'12%',sortable:false,align:'center',hidden:true},
						{name:'expDate',label:'失效日期',width:'12%',sortable:false,align:'center',hidden:true},
						{name:'dmTaskId',label:'执行方式',width:'12%',sortable:false,align:'center',hidden:true},
						{name:'planGoing',label:'计划进度',width:'11%',sortable:false,align:'center',formatter:function(cellval, opts, rwdat, _act){ return planGoingFormatter(cellval, opts, rwdat, _act);}},
						{name:'execType',label:'执行方式',width:'8%',sortable:false,align:'center',formatter:function(cellval){return cellval==1 ? '自动执行' : (cellval==2 ? '手工执行' : '-')}},
						{name:'taskName',label:'策略组',width:'15%',sortable:false,align:'center'},
						{name:'monitorDetail',label:'策略明细',width:'14%',sortable:false,title:false,formatter:function(cellval, opts, rwdat, _act){ return monitorDetailFormatter(cellval, opts, rwdat, _act);}},
						{name:'goingDetail',label:'执行细节',width:'33%',sortable:false,align:'center',formatter:function(cellval, opts, rwdat, _act){ return goingDetailFormatter(cellval, opts, rwdat, _act);}},
						{name:'taskStartTime',label:'开始时间',width:'8%',sortable:false,align:'center'},
						{name:'taskEndTime',label:'预计完成时间',width:'8%',sortable:false,align:'center'},//,formatter:'actions',formatoptions:{delbutton: true,}
					],
					rowNum : 10,
					rowList : [5,10,20],
					recordtext:'第{0}~{1}条/共{2}条',
					pgtext:'第{0}页/共{1}页',
					pginput: false,//是否显示输入框
//			    	viewrecords: false,//是否显示记录描述
					pager: true,
					height:'auto',
					scrollOffset:0,
					server: true,
				    jsonReader : {
			            root: "resultList",// json中代表实际模型数据的入口  
			            page: "page",//当前页
			            total: "totalPages",// json中代表页码总数的数据  
			            records: "totalRecords",//总记录数
			            repeatitems: false,// 如果设为false，则jqGrid在解析json时，会根据name来搜索对应的数据元素（即可以json中元素可以不按顺序）；而所使用的name是来自于colModel中的name设定。
			            cell: "cell",
			            id: "dmPlanId"
			        },
				  pageData: getPerData ,//同步场景直接用getPerData,通过 jQuery("#jqGrid01").jqGrid("reloadData",getPerData(1));加载数据;异步场景用getPerData2
					forceFit:true,  //当为ture时,调整列宽度不会改变表格的宽度
					gridview : false,
					gridComplete:function () {//数据加载完成触发的事件
           			 crt($("#monitor_jqGrid").find(".ui-jqgrid-btable")[0],[0]);
        		}
				};
			$("#monitor_jqGrid").grid(monitoring_opt);
	    getPerData2(1);//默认加载第一页数据
	   
		function crt(ts,cols){   //表格合并
	        var rs = ts.rows;
	        var up=0,sci=0,dci=0;
	        var scv,dcv;
	        var scs=new Array();
	        for(var j=0;j<cols.length;j++){
	            scv=null,up=0;
	            for(var i=0;i<rs.length-1;i++){
	                if(scs[i]==null) scs[i]=0; 
	                if(scs[i+1]==null) scs[i+1]=0; 
	                if(scv==null){
	                    sci=cols[j]-scs[i];
	                    scv=rs[i].cells[sci].innerText;
	                }
	                dci=cols[j]-scs[i+1];
	                dcv=rs[i+1].cells[dci].innerText;
	                if(scv==dcv&&dcv!=' '){
	                    scs[i+1]++;
	                    rs[i+1].deleteCell(dci);
	                    rs[i-up].cells[sci].rowSpan++;
	                    up++;
	                }else{
	                    scv=null,up=0;
	                }
	            }
	        }
		    } ;
	});

		$('#startTaskBtn').bind('click', saveBtnEven);
		function saveBtnEven(){
			$('#startTaskBtn').unbind('click');
			var str="";
	    $('input[type="checkbox"]:checked').each(function(){
	    	if($(this).attr("labelId")){
	     	str+=$(this).attr("labelId")+",";
	     }
	    })
	    if(str!=""||str!=undefined){
	    	str=str.substring(0,str.length-1); 
	    }
	   	if(str.length==0){
	   		//fish.info("请至少选择一条记录!");
	   		$('#startTaskBtn').bind('click', saveBtnEven);
	   		 fish.toast('info','请至少选择一条记录');	
	   	}else{
				$.ajax({
					url : webRoot + 'taskgenerator/dmtaskstage/startTask.do',
					type : 'POST',
					async : true,
					data : {dmPlanIdStr: str}
				}).done(function(serverData, textStatus, jqXHR) {
						//fish.info(serverData);
						if(serverData.length<1){
							fish.toast('error','启动失败');
						}else if(serverData[0]=="0"){
							fish.toast('error',serverData[1]);
						}else{
							for(var j=0;j<serverData.length;j++){
								fish.toast('success',serverData[j]);
								/*$('#startTaskBtn').bind('click', saveBtnEven);	*/
							}
						}
						//fish.toast(serverData, {type : 'success'});	
						page = $("#monitor_jqGrid").jqGrid("getGridParam","page");
						getPerData2(page);										
				}).fail(function() {
					fish.toast('error','网络连接失败');
				}).always(function() {
					$('#startTaskBtn').bind('click', saveBtnEven);
					$.unblockUI();
					
				})
			}
		}

	   	 // 启动按钮操作
		/*$('#startTaskBtn').click(function() {
			var str="";
	    $('input[type="checkbox"]:checked').each(function(){
	    	if($(this).attr("labelId")){
	     	str+=$(this).attr("labelId")+",";
	     }
	    })
	    if(str!=""||str!=undefined){
	    	str=str.substring(0,str.length-1); 
	    }
	   	if(str.length==0){
	   		//fish.info("请至少选择一条记录!");
	   		 fish.toast('info','请至少选择一条记录');	
	   	}else{
				$.ajax({
					url : webRoot + 'taskgenerator/dmtaskstage/startTask.do',
					type : 'POST',
					async : true,
					data : {dmPlanIdStr: str}
				}).done(function(serverData, textStatus, jqXHR) {
						//fish.info(serverData);
						if(serverData.length<1){
							fish.toast('error','启动失败');
						}else if(serverData[0]=="0"){
							fish.toast('error',serverData[1]);
						}else{
							for(var j=0;j<serverData.length;j++){
								fish.toast('success',serverData[j]);
								$('#startTaskBtn').bind('click', saveBtnEven);	
							}
						}
						//fish.toast(serverData, {type : 'success'});	
						page = $("#monitor_jqGrid").jqGrid("getGridParam","page");
						getPerData2(page);										
				}).fail(function() {
					fish.toast('error','网络连接失败');
				}).always(function() {
					$.unblockUI();
					$('#startTaskBtn').bind('click', saveBtnEven);
				})
			}
	 	});*/
	 	 // 立即暂停按钮操作
		$('#immediPauseTaskBtn').click(function() {
			
			var str="";
	    $('input[type="checkbox"]:checked').each(function(){
	    	if($(this).attr("labelId")){
	     	str+=$(this).attr("labelId")+",";
	     }
	    })
	    if(str!=""||str!=undefined){
	    	str=str.substring(0,str.length-1); 
	    }
	   	if(str.length==0){
	   		//fish.showToast("请至少选择一条记录!", {type : 'success'});
	   		//return false;
	   		 fish.toast('info','请至少选择一条记录');	
	   	}else{
				$.ajax({
					url : webRoot + 'taskgenerator/dmtaskstage/immediatelyPause.do',
					type : 'POST',
					async : true,
					data : {dmPlanIdStr: str}
				}).done(function(serverData, textStatus, jqXHR) {
					//fish.info(serverData);
					if(serverData.length<1){
						fish.toast('error','立即暂停失败');
						}else{
							for(var j=0;j<serverData.length;j++){
								fish.toast('success',serverData[j]);	
							}
					}
					page = $("#monitor_jqGrid").jqGrid("getGridParam","page");
				  getPerData2(page);
		
				}).fail(function() {
					fish.toast('error','网络连接失败');
				}).always(function() {
					$.unblockUI();
				})
			}
	 	});
	 	
	 	 // 延时暂停按钮操作
		$('#delayPauseTaskBtn').click(function() {
			
			var str="";
	    $('input[type="checkbox"]:checked').each(function(){
	    	if($(this).attr("labelId")){
	     	str+=$(this).attr("labelId")+",";
	     }
	    })
	    if(str!=""||str!=undefined){
	    	str=str.substring(0,str.length-1); 
	    }
	   	if(str.length==0){
	   		 fish.toast('info','请至少选择一条记录');	
	   	}else{
				$.ajax({
					url : webRoot + 'taskgenerator/dmtaskstage/delayPause.do',
					type : 'POST',
					async : true,
					data : {dmPlanIdStr: str}
				}).done(function(serverData, textStatus, jqXHR) {
					
							//fish.info(serverData);		
							if(serverData.length<1){
							fish.toast('error','延时暂停失败');
							}else{
							for(var j=0;j<serverData.length;j++){
								fish.toast('success',serverData[j]);
							}
						}
							page = $("#monitor_jqGrid").jqGrid("getGridParam","page");
							getPerData2(page);
					
				}).fail(function() {
					fish.toast('error','网络连接失败');
				}).always(function() {
					$.unblockUI();
				})
			}
	 	});
	 	
	 	 // 取消按钮操作
		$('#cancelTaskBtn').click(function() {
			
			var str="";
	    $('input[type="checkbox"]:checked').each(function(){
	    	if($(this).attr("labelId")){
	     	str+=$(this).attr("labelId")+",";
	     }
	    })
	   
	    if(str!=""||str!=undefined){
	    	str=str.substring(0,str.length-1); 
	    }
	   	if(str.length==0){
	   	 fish.toast('info','请至少选择一条记录');	
	   	}else{
				$.ajax({
					url : webRoot + 'taskgenerator/dmtaskstage/cancelTask.do',
					type : 'POST',
					async : true,
					data : {dmPlanIdStr: str}
				}).done(function(serverData, textStatus, jqXHR) {
						//fish.info(serverData);	
						if(serverData.length<1){
								fish.toast('error','取消失败');
						}else{
							for(var j=0;j<serverData.length;j++){
								fish.toast('success',serverData[j]);
							}
						}
						page = $("#monitor_jqGrid").jqGrid("getGridParam","page");
						getPerData2(page);
					
				}).fail(function() {
						fish.toast('error','网络连接失败');
				}).always(function() {
					$.unblockUI();
				})
			}
	 	});